//
//  NotesTableViewCell.m
//  TravelFirst
//
//  Created by lanou on 15/9/19.
//  Copyright (c) 2015年 吴娅君. All rights reserved.
//

#import "NotesTableViewCell.h"
#import "PicturesShowCollectionViewCell.h"
#import "NotesLiveCollectionViewCell.h"
#define kFont [UIFont systemFontOfSize:12]
#define kDescriptionWidth 275
#define kNameButtonHeight 15

@implementation NotesTableViewCell


#pragma mark - init -

- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
    if (self = [super initWithStyle:style reuseIdentifier:reuseIdentifier]) {
        self.backgroundColor = [UIColor clearColor];
        self.selectionStyle = UITableViewCellSelectionStyleNone;
        
        self.backgroundImageView = [[UIView alloc] init];
        self.backgroundImageView.backgroundColor = [UIColor whiteColor];
        [self.contentView addSubview:self.backgroundImageView];
        
        // 作者头像
        self.nicknameImageView = [UIButton buttonWithType:UIButtonTypeCustom];
        self.nicknameImageView.frame = CGRectMake(10, 10, 40, 40);
        self.nicknameImageView.layer.masksToBounds = YES;
        self.nicknameImageView.layer.cornerRadius = self.nicknameImageView.width / 2;
        //self.nicknameImageView.backgroundColor = [UIColor redColor];
        [self.backgroundImageView addSubview:self.nicknameImageView];
        
        // 作者名字
        self.nicknameLabel = [[UILabel alloc] initWithFrame:CGRectMake(self.nicknameImageView.right + 10, self.nicknameImageView.top + 2, 150, 20)];
        //self.nicknameButton.backgroundColor = [UIColor blueColor];
        self.nicknameLabel.textColor = [UIColor colorWithRed:38 % 256 / 255.0 green:156 % 256 / 255.0 blue:197 % 256 / 255.0 alpha:1];
        [self.backgroundImageView addSubview:self.nicknameLabel];
        
        // 图片数量
        self.picturesNumberLabel = [[UILabel alloc] initWithFrame:CGRectMake(self.nicknameLabel.left, self.nicknameLabel.bottom + 5, 100, 13)];
        self.picturesNumberLabel.font = kFont;
        self.picturesNumberLabel.textColor = kColor;
        //self.picturesNumberLabel.backgroundColor = [UIColor whiteColor];
        [self.backgroundImageView addSubview:self.picturesNumberLabel];
        
        // 更新时间
        self.updateTimeLabel = [[UILabel alloc] initWithFrame:CGRectMake(kWidth - 20 - 10 - 100, self.picturesNumberLabel.top, 100, 13)];
        self.updateTimeLabel.textAlignment = NSTextAlignmentRight;
        //self.updateTimeLabel.backgroundColor = [UIColor redColor];
        self.updateTimeLabel.font = kFont;
        self.updateTimeLabel.textColor = kColor;
        [self.backgroundImageView addSubview:self.updateTimeLabel];
        
        // 图片展示
        UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
        self.picturesShowCollectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, self.picturesNumberLabel.bottom + 5, kWidth - 20, kWidth - 20) collectionViewLayout:flowLayout];
        self.picturesShowCollectionView.backgroundColor = [UIColor whiteColor];
        self.picturesShowCollectionView.scrollEnabled = NO;
        [self.backgroundImageView addSubview:self.picturesShowCollectionView];
        
        // 更多图片
        self.morePicturesButton = [UIButton buttonWithType:UIButtonTypeCustom];
        self.morePicturesButton.frame = CGRectMake((kWidth - 20 - 100) / 2, self.picturesShowCollectionView.bottom + 10, 100, 30);
        [self.morePicturesButton setTitle:@"更多图片..." forState:(UIControlStateNormal)];
        [self.morePicturesButton setTitleColor:[UIColor blueColor] forState:(UIControlStateNormal)];
        [self.backgroundImageView addSubview:self.morePicturesButton];
        
        UIView *lineView = [[UIView alloc] initWithFrame:CGRectMake(0, self.morePicturesButton.bottom + 10, kWidth, 1)];
        lineView.backgroundColor = kColor;
        lineView.tag = 100;
        [self.backgroundImageView addSubview:lineView];
        
        // 图片标题
        self.nameImageView = [[UIImageView alloc] initWithFrame:CGRectMake(15, self.morePicturesButton.bottom + 30, kNameButtonHeight, kNameButtonHeight)];
        self.nameImageView.backgroundColor = [UIColor blackColor];
        [self.backgroundImageView addSubview:self.nameImageView];
        self.nameButton = [UIButton buttonWithType:UIButtonTypeCustom];
        self.nameButton.frame = CGRectMake(self.nameImageView.right + 10, self.nameImageView.top - 7, 150, 15);
        [self.nameButton setTitleColor:[UIColor purpleColor] forState:(UIControlStateNormal)];
        //self.nameButton.backgroundColor = [UIColor purpleColor];
        [self.backgroundImageView addSubview:self.nameButton];
        
        // 定位地址
        self.locationImageView = [[UIImageView alloc] init];
        [self.backgroundImageView addSubview:self.locationImageView];
        self.locationLabel = [[UILabel alloc] init];
        [self.backgroundImageView addSubview:self.locationLabel];
        
        // 图片描述
        self.descriptionImageView = [[UIImageView alloc] init];
        [self.backgroundImageView addSubview:self.descriptionImageView];
        self.descriptionLabel = [[UILabel alloc] init];
        [self.backgroundImageView addSubview:self.descriptionLabel];
        
        // 分割线
        UIView *commentView = [[UIView alloc] init];
        commentView.backgroundColor = kColor;
        commentView.tag = 101;
        [self.backgroundImageView addSubview:commentView];
        
        // 评论内容
        self.commentLabel = [[UILabel alloc] init];
        //self.commentLabel.backgroundColor = [UIColor grayColor];
        self.commentLabel.numberOfLines = 0;
        [self.backgroundImageView addSubview:self.commentLabel];
        
        // 虚线
        UIImageView *praiseView = [[UIImageView alloc] init];
        praiseView.tag = 102;
        [self.backgroundImageView addSubview:praiseView];
        
        // 赞和评论
        self.praiseAndCommentView = [[PraiseAndCommentView alloc] init];
        //self.praiseAndCommentView.backgroundColor = [UIColor grayColor];
        [self.backgroundImageView addSubview:self.praiseAndCommentView];
        
        self.backgroundImageView.frame = CGRectMake(10, 10, kWidth - 20, self.nameButton.bottom + 15);
        self.backgroundImageView.layer.masksToBounds = YES;
        self.backgroundImageView.layer.cornerRadius = 8;
        
    }
    return self;
}


#pragma mark - 设置动态frame -

- (void)setLocationWithFrame:(CGRect)frame string:(NSString *)string
{
    // 定位地址
    self.locationImageView.frame = frame;
    self.locationImageView.backgroundColor = [UIColor redColor];
    
    self.locationLabel.frame = CGRectMake(self.locationImageView.right + 10, self.locationImageView.top, kWidth - 20 - self.locationImageView.right - 10, 15);
    self.locationLabel.backgroundColor = [UIColor blueColor];
    self.locationLabel.text = string;
    
    self.backgroundImageView.frame = CGRectMake(10, 0, kWidth - 20, self.locationImageView.bottom + 5);
}

- (void)setDescriptionWithFrame:(CGRect)frame
{
    // 图片描述
    self.descriptionImageView.frame = frame;
    self.descriptionImageView.backgroundColor = [UIColor grayColor];
    
    self.descriptionLabel.frame = CGRectMake(self.descriptionImageView.right + 10, self.descriptionImageView.top, kWidth - 20 - (self.descriptionImageView.right + 10) * 2, kNameButtonHeight);
    self.descriptionLabel.numberOfLines = 0;
    self.descriptionLabel.backgroundColor = [UIColor greenColor];
}

- (void)setCommentLabelWithFrame:(CGRect)frame nicknameString:(NSString *)nicknameString contentString:(NSString *)contentString
{
    NSMutableAttributedString *attributedString = [self transformStringColor:nicknameString];
    NSMutableAttributedString *contentAttributedString = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@": %@", contentString]];
    [attributedString appendAttributedString:contentAttributedString];
    if (self.commentLabel.text && self.commentLabel.text.length != 0) {
        NSMutableAttributedString *prefixString = [[NSMutableAttributedString alloc] initWithString:@"\n"];
        [attributedString insertAttributedString:prefixString atIndex:0];
        NSMutableAttributedString *commentAttributedStr = [[NSMutableAttributedString alloc] initWithAttributedString:self.commentLabel.attributedText];
        [commentAttributedStr appendAttributedString:attributedString];
        self.commentLabel.attributedText = commentAttributedStr;
    } else {
        self.commentLabel.attributedText = attributedString;
    }
    CGFloat height = [NotesTableViewCell setLabelHeightWithString:self.commentLabel.text width:frame.size.width];
    self.commentLabel.frame = CGRectMake(frame.origin.x, frame.origin.y, frame.size.width, height);
    UIView *commentView = [self.contentView viewWithTag:101];
    commentView.frame = CGRectMake(frame.origin.x, frame.origin.y - 15, frame.size.width, 1);
}


- (void)setPraiseAndCommentViewWithFrame:(CGRect)frame model:(NotesModel *)model
{
    self.praiseAndCommentView.frame = frame;
    if (model.comment_count && ![model.comment_count isEqualToString:@"0"]) {
        self.praiseAndCommentView.commentLabel.text = model.comment_count;
    }
    if (model.fav_count && ![model.fav_count isEqualToString:@"0"]) {
        self.praiseAndCommentView.praiseLabel.text = model.comment_count;
    }
    [self dashedLineWithFrame:CGRectMake(0, frame.origin.y, kWidth - 20, 1)];
}

+ (CGFloat)setCellHeightWithModel:(NotesModel *)model
{
    NotesModel *notesModel = [[NotesModel alloc] init];
    [notesModel shareJsonWithDictionary:model.postsArray[0]];
    notesModel.posts_description = model.postsArray[0][@"description"];
    
    CGFloat locationLabelHeight = 0;
    if (notesModel.location && notesModel.location.length != 0) {
        locationLabelHeight = 10 + 15;
    }
    
    CGFloat descriptionLabelHeight = 0;
    if (notesModel.posts_description && notesModel.posts_description.length != 0) {
        descriptionLabelHeight = [NotesTableViewCell setLabelHeightWithString:notesModel.posts_description width:kDescriptionWidth] + 10;
    }
    
    CGFloat commentLabelHeight = 0;
    if (model.comments && model.comments.count != 0) {
        commentLabelHeight = [NotesTableViewCell setLabelHeightWithString:model.string width:kDescriptionWidth] + 30;
    }
    
    CGFloat praiseViewHeight = 70;
    CGFloat height = 20 + kNameButtonHeight;
    CGFloat moreButtonHeight = 85;
    
    CGFloat tempHeight = locationLabelHeight + descriptionLabelHeight + commentLabelHeight + praiseViewHeight + 10;
    
    NSInteger count = [model.added_post_count intValue];
    if (count < 7 && count > 3) {
        return 289 + height + tempHeight;
    } else if (count < 4 && count > 1) {
        return 167 + height + tempHeight;
    } else if (count == 1 || (count > 6 && count < 10)) {
        return 410 + height + tempHeight;
    } else {
        return 410 + moreButtonHeight + tempHeight;
    }
}


#pragma mark - 赋值 -

- (void)setFrameWithModel:(NotesModel *)model
{
    NSInteger count = [model.added_post_count intValue];
    if (count < 7 && count > 3) {
        self.picturesShowCollectionView.frame = CGRectMake(0, 55, 355, 2 * (kWidth - 20 - 20) / 3 + 10);
        self.morePicturesButton.frame = CGRectZero;
        
        UIView *lineView = [self.backgroundImageView viewWithTag:100];
        lineView.frame = CGRectZero;
        
        self.nameImageView.frame = CGRectMake(15, self.picturesShowCollectionView.bottom + 20, kNameButtonHeight, kNameButtonHeight);
        self.nameButton.frame = CGRectMake(self.nameImageView.right + 10, self.nameImageView.top - 7, 150, kNameButtonHeight);
        
    } else if (count < 4 && count > 1) {
        self.picturesShowCollectionView.frame = CGRectMake(0, 55, 355, (kWidth - 20 - 20) / 3);
        self.morePicturesButton.frame = CGRectZero;
        
        UIView *lineView = [self.backgroundImageView viewWithTag:100];
        lineView.frame = CGRectZero;
        
        self.nameImageView.frame = CGRectMake(15, self.picturesShowCollectionView.bottom + 20, kNameButtonHeight, kNameButtonHeight);
        self.nameButton.frame = CGRectMake(self.nameImageView.right + 10, self.nameImageView.top - 7, 150, 15);
        
    } else if (count == 1 || (count > 6 && count < 10)) {
        self.picturesShowCollectionView.frame = CGRectMake(0, 55, 355, 3 * (kWidth - 20 - 20) / 3 + 20);
        self.morePicturesButton.frame = CGRectZero;
        
        UIView *lineView = [self.backgroundImageView viewWithTag:100];
        lineView.frame = CGRectZero;
        
        self.nameImageView.frame = CGRectMake(15, self.picturesShowCollectionView.bottom + 20, kNameButtonHeight, kNameButtonHeight);
        self.nameButton.frame = CGRectMake(self.nameImageView.right + 10, self.nameImageView.top - 7, 150, kNameButtonHeight);
        
    } else {
        self.picturesShowCollectionView.frame = CGRectMake(0, 55, 355, 3 * (kWidth - 20 - 20) / 3 + 20);
        self.morePicturesButton.frame = CGRectMake((kWidth - 20 - 100) / 2, self.picturesShowCollectionView.bottom + 10, 100, 30);
        
        UIView *lineView = [self.backgroundImageView viewWithTag:100];
        lineView.frame = CGRectMake(0, self.morePicturesButton.bottom + 10, kWidth, 1);
        
        self.nameImageView.frame = CGRectMake(15, self.morePicturesButton.bottom + 30, kNameButtonHeight, kNameButtonHeight);
        self.nameButton.frame = CGRectMake(self.nameImageView.right + 10, self.nameImageView.top - 7, 150, kNameButtonHeight);
    }
    
    [self setValueWithModel:model];
}


- (void)setValueWithModel:(NotesModel *)model
{
    // 头像
    [self.nicknameImageView sd_setBackgroundImageWithURL:[NSURL URLWithString:model.avatar] forState:UIControlStateNormal placeholderImage:nil];
    // 作者
    self.nicknameLabel.text = model.nickname;
    // 图片数量
    self.picturesNumberLabel.text = [NSString stringWithFormat:@"更新了%@张图片", model.added_post_count];
    // 更新时间
    self.updateTimeLabel.text = [self dateTransformWith:model.log_created_date];
    
    // 图片标题
    [self.nameButton setTitle:model.name forState:(UIControlStateNormal)];
    self.nameButton.titleLabel.font = [UIFont systemFontOfSize:15];
    [self.nameButton sizeToFit];
    
    NotesModel *notesModel = [[NotesModel alloc] init];
    [notesModel shareJsonWithDictionary:model.postsArray[0]];
    notesModel.posts_description = model.postsArray[0][@"description"];
    
    [self sssModel:notesModel];
    [self setCommentLabelAndPraiseAndCommentViewWithModel:model];
}

- (void)sssModel:(NotesModel *)notesModel
{
    BOOL isLocation = notesModel.location && notesModel.location.length != 0;
    if (isLocation) {
        CGRect frame = CGRectMake(self.nameImageView.left, self.nameImageView.bottom + 15, 15, 15);
        [self setLocationWithFrame:frame string:notesModel.location];
    }
    
    BOOL isDescription = notesModel.posts_description && notesModel.posts_description.length != 0;
    if (isDescription) {
        if (isLocation) {
            CGRect descriptionFrame1 = CGRectMake(self.locationImageView.left, self.locationImageView.bottom + 15, 15, 15);
            [self setDescriptionWithFrame:descriptionFrame1];
        } else {
            CGRect descriptionFrame2 = CGRectMake(self.nameImageView.left, self.nameImageView.bottom + 15, 15, 15);
            [self setDescriptionWithFrame:descriptionFrame2];
        }
        
        self.descriptionLabel.text = notesModel.posts_description;
        
        CGFloat height = [NotesTableViewCell setLabelHeightWithString:self.descriptionLabel.text width:kDescriptionWidth];
        self.descriptionLabel.frame = CGRectMake(self.descriptionImageView.right + 10, self.descriptionImageView.top, kWidth - 20 - (self.descriptionImageView.right + 10) * 2, height);
        self.backgroundImageView.frame = CGRectMake(10, 0, kWidth - 20, self.descriptionLabel.bottom + 5);
    }

}


- (void)setCommentLabelAndPraiseAndCommentViewWithModel:(NotesModel *)model
{
    if (model.comments && model.comments.count != 0) {
        for (NSDictionary *commentDic in model.comments) {
            NotesModel *notesModel = [[NotesModel alloc] init];
            [notesModel shareJsonWithDictionary:commentDic];
            [notesModel shareJsonWithDictionary:commentDic[@"created_by"]];
            CGRect frame = CGRectZero;
            if (self.descriptionLabel.height != 0) {
                frame = CGRectMake(self.descriptionLabel.left, self.descriptionLabel.bottom + 30, kDescriptionWidth, 30);
            } else if (self.locationLabel.height != 0) {
                frame = CGRectMake(self.locationLabel.left, self.locationLabel.bottom + 30, kDescriptionWidth, 30);
            } else {
                frame = CGRectMake(self.nameButton.left, self.nameButton.bottom + 30, kDescriptionWidth, 30);
            }
            [self setCommentLabelWithFrame:frame nicknameString:notesModel.nickname contentString:notesModel.content];
        }
        // 计算cell高度时所需要的commentLabel最后高度字符串
        model.string = self.commentLabel.text;
        CGRect frame = CGRectMake(0, self.commentLabel.bottom + 10, kWidth - 20, 50);
        [self setPraiseAndCommentViewWithFrame:frame model:model];
        
    } else {
        CGRect frame = CGRectZero;
        if (self.descriptionLabel.height != 0) {
            frame = CGRectMake(0, self.descriptionLabel.bottom + 10, kWidth - 20, 50);
        } else if (self.locationLabel.height != 0) {
            frame = CGRectMake(0, self.locationLabel.bottom + 10, kWidth - 20, 50);
        } else {
            frame = CGRectMake(0, self.nameButton.bottom + 10, kWidth - 20, 50);
        }
        [self setPraiseAndCommentViewWithFrame:frame model:model];
    }
    
    self.backgroundImageView.frame = CGRectMake(10, 0, kWidth - 20, self.praiseAndCommentView.bottom + 5);
}


#pragma mark - 其他 -

+ (float)setLabelHeightWithString:(NSString *)string width:(CGFloat)width
{
    CGRect frame = [string boundingRectWithSize:CGSizeMake(width, 1000) options:NSStringDrawingUsesLineFragmentOrigin attributes:[NSDictionary dictionaryWithObject:[UIFont systemFontOfSize:17] forKey:NSFontAttributeName] context:nil];
    return frame.size.height;
}

- (void)setTarget:(id)target moreButtonAction:(SEL)moreButtonAction nameButtonAction:(SEL)nameButtonAction nicknameButtonAction:(SEL)nicknameButtonAction index:(NSInteger)index
{
    self.picturesShowCollectionView.delegate = target;
    self.picturesShowCollectionView.dataSource = target;
    
    [self.morePicturesButton addTarget:target action:moreButtonAction forControlEvents:UIControlEventTouchUpInside];
    self.morePicturesButton.tag = 1000 + index;
    
    [self.nameButton addTarget:target action:nameButtonAction forControlEvents:UIControlEventTouchUpInside];
    self.nameButton.tag = 10000 + index;
    
    self.picturesShowCollectionView.tag = 100000 + index;
    
    [self.nicknameImageView addTarget:target action:nicknameButtonAction forControlEvents:UIControlEventTouchUpInside];
    self.nicknameImageView.tag = 500 + index;
}

- (void)setPraiseAndCommentWithTarget:(id)target tapAction:(SEL)tapAction praiseAction:(SEL)praiseAction commentAction:(SEL)commentAction index:(NSInteger)index
{
    [self.praiseAndCommentView setTarget:target praiseAction:praiseAction commentAction:commentAction index:index];
    [self addTapGestureRecognizerWithTarget:target action:tapAction index:index];
}

- (NSMutableAttributedString *)transformStringColor:(NSString *)string
{
    NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:string];
    [attributedString addAttribute:NSForegroundColorAttributeName value:[UIColor blueColor] range:NSMakeRange(0, string.length)];
    return attributedString;
}

// 时间戳转时间 计算出更新了多长时间
- (NSString *)dateTransformWith:(NSString *)dateStr
{
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyy/MM/dd HH:mm:ss"];
    NSDate *date = [NSDate dateWithTimeIntervalSince1970:[dateStr floatValue]];
    NSDate *nowDate = [NSDate date];
    
    NSTimeInterval seconds = [nowDate timeIntervalSinceDate:date];
    seconds = fabs(seconds);
    if (seconds < 60) {
        return [NSString stringWithFormat:@"%.0lf秒前", seconds];
    } else if (seconds > 60 && seconds < 3600) {
        return [NSString stringWithFormat:@"%.0lf分钟前", seconds / 60];
    } else if (seconds > 3600 && seconds < 86400) {
        return [NSString stringWithFormat:@"%.0lf小时前", seconds / 3600];
    } else if (seconds > 86400 && seconds < 2592000) {
        return [NSString stringWithFormat:@"%.0lf天前", seconds / 86400];
    } else if (seconds > 2592000 && seconds < 31104000) {
        return [NSString stringWithFormat:@"%.0lf个月前", seconds / 2592000];
    } else {
        return [NSString stringWithFormat:@"%.0lf年前", seconds / 31104000];
    }
    
    return nil;
}

// 虚线
- (void)dashedLineWithFrame:(CGRect)frame
{
    UIImageView *praiseView = (UIImageView *)[self.backgroundImageView viewWithTag:102];
    praiseView.frame = frame;
    // 开始画线
    UIGraphicsBeginImageContext(praiseView.frame.size);
    
    [praiseView.image drawInRect:CGRectMake(0, 0, praiseView.frame.size.width, praiseView.frame.size.height)];
    // 设置线条终点形状
    CGContextSetLineCap(UIGraphicsGetCurrentContext(), kCGLineCapRound);
    // 先画6个点再画3个点
    CGFloat lengths[] = {6, 3};
    
    CGContextRef line = UIGraphicsGetCurrentContext();
    CGContextSetStrokeColorWithColor(line, kColor.CGColor);
    
    // 画虚线
    CGContextSetLineDash(line, 0, lengths, 2);
    // 开始画线
    CGContextMoveToPoint(line, 0, praiseView.frame.size.height);
    CGContextAddLineToPoint(line, praiseView.frame.size.width, praiseView.frame.size.height);
    
    CGContextStrokePath(line);
    praiseView.image = UIGraphicsGetImageFromCurrentImageContext();
    
}

- (void)addTapGestureRecognizerWithTarget:(id)target action:(SEL)action index:(NSInteger)index
{
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:target action:action];
    [self.commentLabel addGestureRecognizer:tap];
    self.commentLabel.userInteractionEnabled = YES;
    self.commentLabel.tag = 1000000 + index;
}



- (void)awakeFromNib {
    // Initialization code
}

- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
    [super setSelected:selected animated:animated];

    // Configure the view for the selected state
}



@end
